package com.tjian.fafa.user.module.extend;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.tjian.fafa.user.R;
import com.tjian.fafa.user.base.ConnectedApp;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.mainBody.MainBodyActivity;
import com.tjian.fafa.user.module.courier.activity.BikeExpressageActivity;
import com.tjian.fafa.user.module.home.adapter.NewsAdapter;
import com.tjian.fafa.user.module.home.bean.NewsEntity;
import com.tjian.fafa.user.module.home.fragment.BicycleFragment;
import com.tjian.fafa.user.module.home.tool.Constants_home;
import com.tjian.util.NetUtil;

import java.util.ArrayList;


public class Fafa_instant_delivery_activity extends Activity implements OnGetGeoCoderResultListener
{
    ArrayList<NewsEntity> newsList = new ArrayList<NewsEntity>();
    ListView mListView;
    NewsAdapter mAdapter;

    ImageView detail_loading;
    public final static int SET_NEWSLIST = 0;

    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;

    MapView mMapView;
    BaiduMap mBaiduMap;

    // UI相关
    RadioGroup.OnCheckedChangeListener radioButtonListener;
    Button requestLocButton;
    boolean isFirstLoc = true; // 是否首次定位
    GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE); //requestWindowFeature(Window.FEATURE_NO_TITLE); 这个在Android里用来隐藏标题栏的函数.
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        setContentView(R.layout.news_fragment);

        SDKInitializer.initialize(getApplicationContext());//实例化百度地图
        initData();
        setUserVisibleHint(true);
        createHomePageBaiduMap();//加载地图
        initOLdNewsListView();//加载旧的新闻列表
        showDiliverymanByLatAndLon();//显示周边配送员
    }

    /**
     * 此方法意思为fragment是否可见 ,可见时候加载数据
     */
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        if (isVisibleToUser)
        {
            //fragment可见时加载数据
            if (newsList != null && newsList.size() != 0)
            {
                handler.obtainMessage(SET_NEWSLIST).sendToTarget();
            }
            else
            {
                new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            Thread.sleep(2);
                        }
                        catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                        handler.obtainMessage(SET_NEWSLIST).sendToTarget();
                    }
                }).start();
            }
        }
        else
        {
            //fragment不可见时不执行操作
        }

    }

    private void initData()
    {
        newsList = Constants_home.getNewsList();
    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case SET_NEWSLIST:
                    detail_loading.setVisibility(View.GONE);
                    mAdapter = new NewsAdapter(Fafa_instant_delivery_activity.this, newsList);
                    mListView.setAdapter(mAdapter);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener
    {

        @Override
        public void onReceiveLocation(BDLocation location)
        {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
            {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc)
            {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation)
        {
        }
    }

    //首页地图
    public void createHomePageBaiduMap()
    {
        requestLocButton = (Button) findViewById(R.id.button1);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        requestLocButton.setText("普通");
        View.OnClickListener btnClickListener = new View.OnClickListener()
        {
            public void onClick(View v)
            {
                switch (mCurrentMode)
                {
                    case NORMAL:
                        requestLocButton.setText("跟随");
                        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
                        mBaiduMap
                                .setMyLocationConfigeration(new MyLocationConfiguration(
                                        mCurrentMode, true, mCurrentMarker));
                        break;
                    case COMPASS:
                        requestLocButton.setText("普通");
                        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
                        mBaiduMap
                                .setMyLocationConfigeration(new MyLocationConfiguration(
                                        mCurrentMode, true, mCurrentMarker));
                        break;
                    case FOLLOWING:
                        requestLocButton.setText("罗盘");
                        mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS;
                        mBaiduMap
                                .setMyLocationConfigeration(new MyLocationConfiguration(
                                        mCurrentMode, true, mCurrentMarker));
                        break;
                    default:
                        break;
                }
            }
        };
        requestLocButton.setOnClickListener(btnClickListener);

        RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup);
        radioButtonListener = new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                if (checkedId == R.id.defaulticon)
                {
                    // 传入null则，恢复默认图标
                    mCurrentMarker = null;
                    mBaiduMap
                            .setMyLocationConfigeration(new MyLocationConfiguration(
                                    mCurrentMode, true, null));
                }
                if (checkedId == R.id.customicon)
                {
                    // 修改为自定义marker
                    mCurrentMarker = BitmapDescriptorFactory
                            .fromResource(R.drawable.f000);
                    mBaiduMap
                            .setMyLocationConfigeration(new MyLocationConfiguration(
                                    mCurrentMode, true, mCurrentMarker));
                }
            }
        };
        group.setOnCheckedChangeListener(radioButtonListener);

        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(Fafa_instant_delivery_activity.this);
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }


    public void initOLdNewsListView()
    {
        mListView = (ListView) findViewById(R.id.mListView);
        detail_loading = (ImageView) findViewById(R.id.detail_loading);
    }

    /**
     * 解码周边的配送员，用图标显示出来
     */
    public void showDiliverymanByLatAndLon()
    {
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        LatLng ptCenter = new LatLng((Float.valueOf("39.904965")), (Float.valueOf("116.327764")));
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));// 反Geo搜索

        //        LatLng ptCenter2 = new LatLng((Float.valueOf("39.904965")), (Float.valueOf("116.327764")));
        LatLng ptCenter2 = new LatLng((Float.valueOf("39.914965")), (Float.valueOf("116.317764")));
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter2));// 反Geo搜索
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result)
    {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR)
        {
            Toast.makeText(Fafa_instant_delivery_activity.this, "抱歉，未能找到结果_20160203_110350", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_marka)));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
                .getLocation()));
        String strInfo = String.format("纬度：%f 经度：%f",
                result.getLocation().latitude, result.getLocation().longitude);
        Toast.makeText(Fafa_instant_delivery_activity.this, strInfo, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result)
    {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR)
        {
            Toast.makeText(Fafa_instant_delivery_activity.this, "抱歉，未能找到结果_20160203_110358", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_marka)));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
                .getLocation()));
        Toast.makeText(Fafa_instant_delivery_activity.this, result.getAddress(),
                Toast.LENGTH_LONG).show();

    }

    @Override
    public void onPause()
    {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume()
    {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy()
    {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        mSearch.destroy();
        super.onDestroy();
    }

    //下一步
    public void homePageNextStepButtonOnClick(View view)
    {
        Intent intent = new Intent();
        intent.setClass(this, BikeExpressageActivity.class);
        Fafa_instant_delivery_activity.this.startActivity(intent);
    }

}
